<script lang="ts" setup>
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue'

// do not use same name with ref
const form = reactive({
  ID: '',
  name: '',
  ISBN: '',
  author: '',
  publication: '',
  category: '',
  price: '',
  introduction: '',
  count:'',
})

const loading = ref(false)  //用于控制按钮加载状态

const onSubmit = async () => {
  if(!form.ID && !form.name && !form.ISBN && !form.author){
    console.error('图书编号、图书名字、图书ISBN号和图书的作者不能为空')
    return
  }
  try {
    loading.value = true // 提交前开始加载
    const response = await request.post('/book/add', {
      id: form.ID,
      name: form.name,
      isbn: form.ISBN,
      author: form.author,
      publication: form.publication,
      category: form.category,
      price: form.price,
      introduction: form.introduction,
      count:form.count,
    })
    if (response.status === 200 && response.data.status === 'success') {
      console.log('添加图书成功', response.data)
    } 
      ElMessage.success('添加图书成功')
  } catch (error) {
    console.error('Failed to add category:', error)
    ElMessage.error('服务器发生错误，请稍后重试')
  } finally {
    loading.value = false // 请求结束后关闭加载
  }
}
</script>

<template>
    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <el-form-item label="图书编号">
        <el-input v-model="form.ID" placeholder="请输入图书编号" />
      </el-form-item>
      <el-form-item label="书名">
        <el-input v-model="form.name" placeholder="请输入图书书名"/>
      </el-form-item>
      <el-form-item label="ISBN">
        <el-input v-model="form.ISBN" placeholder="请输入图书的ISBN号"/>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="form.author" placeholder="请输入图书的作者"/>
      </el-form-item>
      <el-form-item label="出版社">
        <el-input v-model="form.publication" placeholder="请输入图书的出版社" />
      </el-form-item>
      <el-form-item label="类别">
      <el-select v-model="form.category" placeholder="请选择">
        <el-option label="小说" value="shanghai" />
        <el-option label="历史" value="beijing" />
        <el-option label="计算机" value="beijing" />
        <el-option label="哲学" value="beijing" />
        <el-option label="社会科学" value="beijing" />
      </el-select>
    </el-form-item>
      <el-form-item label="价格" >
        <el-input v-model="form.price" placeholder="￥"/>
      </el-form-item>
      <el-form-item label="数量" >
        <el-input v-model="form.count" placeholder="请输入数量"/>
      </el-form-item>
      <el-form-item label="简介">
        <el-input v-model="form.introduction" type="textarea" placeholder="简介"/>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
</template>
  

<style lang="scss" scoped>

</style>